import Vue from 'vue';
import { Toast } from 'vant'; 
Vue.use(Toast);
import store from '../store';

import axios from "axios";
const service = axios.create({
  baseURL: "http://huruqing.cn:3003/",
  timeout: 50000, // 请求超时时间(因为需要调试后台,所以设置得比较大)
});

// request拦截器
service.interceptors.request.use(
  (config) => {
     // 打开loading
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    });
    // 请求头添加token
    config.headers["user-token"] = store.state.token;
    return config;
  },
  (error) => {
    Toast.fail(res.msg); 
  }
);

// response 拦截器
service.interceptors.response.use(
  (response) => {
    // 关闭loading
    Toast.clear();
    const res = response.data;
    if (res.code == 666) {
      return res;
    } else {
      Toast.fail(res.msg); 
    }
  },
  (error) => { 
    // 关闭loading
    Toast.clear();
    console.log('错误信息:',error);
    Toast.fail('网络异常, 请稍后再试');  
  }
);

export default service;
